package com.baylor.server.business.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baylor.server.base.util.XaUtil;
import com.baylor.server.business.entity.Admin;
import com.baylor.server.business.entity.UserInfo;
import com.baylor.server.business.service.UserInfoService;
import com.baylor.server.business.utils.ExportExcel;
import com.baylor.server.business.utils.FolderPath;
import com.baylor.server.business.utils.LangHelper;

@Controller
@RequestMapping("/user")
public class UserInfoController {
	@Autowired
	private UserInfoService userInfoService;
	
	/**
	 * 用户列表
	 */
	@RequestMapping(value="userList")
	public String userList(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="nextPage", defaultValue="0")Integer nextPage,
			@RequestParam(value="userName",defaultValue="")String userName,
			@RequestParam(value="userPhone",defaultValue="")String userPhone,
			@RequestParam(value="userType",defaultValue="")String userType,
			@RequestParam(value="entraceState",defaultValue="")String entraceState,
			@RequestParam(value="pwd",defaultValue="")String pwd,
			@RequestParam(value="export",defaultValue="")String export){
		Pageable pageable = new PageRequest(nextPage,10,new Sort(new Order(Direction.DESC, "userRegister")));//
		Map<String,Object> filterParams = new HashMap<String,Object>();
 
		filterParams.put("EQ_zhOren",LangHelper.getLang(request));
 
		if(userName!=null && userName.trim().length()>0){
			filterParams.put("LIKE_userName", userName);
		} 
		if(userPhone!=null && userPhone.trim().length()>0){
			filterParams.put("LIKE_userPhone", userPhone);
		}
		if(userType!=null && userType.trim().length()>0){
			filterParams.put("LIKE_userType", userType);
		}
		if(entraceState!=null && entraceState.trim().length()>0){
			filterParams.put("EQ_entraceState", entraceState);
		}
		if(export.contains("批量导出")){
			String [] bootarea=new String[]{"","光通信","LED","精密光学","其他","激光红外"};
			pageable = new PageRequest(nextPage,1000000000,new Sort(new Order(Direction.DESC, "userRegister")));
			Page<UserInfo> data = userInfoService.findUserDataByFilter(filterParams,pageable);
			
			Hashtable<String, String> columnsName =new Hashtable<String, String>();
			columnsName.put("用户编号", "userId");
            columnsName.put("会员帐号", "userLoginName");
            columnsName.put("会员名", "userName");
			columnsName.put("手机号", "userPhone");
			columnsName.put("注册日期", "userRegister");
			columnsName.put("性别", "userSex");
			columnsName.put("状态", "userState");
			columnsName.put("类型", "userType");
			columnsName.put("中英文", "zhOren");
		//	columnsName.put("入场", "entranceState");
			columnsName.put("公司", "userCompany");
			columnsName.put("行业", "industry");
			columnsName.put("Email", "userEmail");
			Hashtable<String, String> columnsName1 =new Hashtable<String, String>();

            List<Hashtable<String,String>> list1 = new  ArrayList<Hashtable<String, String>>();
          
            for(UserInfo user:data.getContent()){
                columnsName1 = new Hashtable<String,String>();
                if (XaUtil.isEmpty(user.getUserId()))
                {
                    columnsName1.put("userId","");
                }else
                {
                    columnsName1.put("userId",user.getUserId()+"");
                }


                if (XaUtil.isEmpty(user.getUserName()))
                {
                    columnsName1.put("userName", "");
                }else
                {
                    columnsName1.put("userName", user.getUserName());
                }

                if (XaUtil.isEmpty(user.getUserPhone()))
                {
                    columnsName1.put("userPhone", "");
                    columnsName1.put("userLoginName", "");
                }else
                {
                    columnsName1.put("userPhone", user.getUserPhone());
                    columnsName1.put("userLoginName", user.getUserPhone());
                }

                if (XaUtil.isEmpty(user.getUserRegister()))
                {
                    columnsName1.put("userRegister", "");
                }else
                {
                    columnsName1.put("userRegister", user.getUserRegister());
                }

                if (XaUtil.isEmpty(user.getUserSex()))
                {
                    columnsName1.put("userSex", "");
                }else
                {
                    columnsName1.put("userSex", user.getUserSex());
                }
				if(user.getUserState()==1){//1:已登录，0:未登录，3:禁止登录，2:激活登陆
					columnsName1.put("userState", "已登录");
				}else if(user.getUserState()==0){//1:已登录，0:未登录，3:禁止登录，2:激活登陆
					columnsName1.put("userState", "未登录");
				}else if(user.getUserState()==2){//1:已登录，0:未登录，3:禁止登录，2:激活登陆
					columnsName1.put("userState", "激活登录");
				}else if(user.getUserState()==3){//1:已登录，0:未登录，3:禁止登录，2:激活登陆
					columnsName1.put("userState", "禁止登录");
				}else
                {
                    columnsName1.put("userState", "");
                }

                if (XaUtil.isEmpty(user.getUserType()))
                {
                    columnsName1.put("userType", "");
                }else
                {
                    columnsName1.put("userType", user.getUserType());
                }
				if(user.getZhOren()==1){
					columnsName1.put("zhOren", "中文");
				}else if(user.getZhOren()==2){
					columnsName1.put("zhOren", "英文");
				}else
                {
                    columnsName1.put("zhOren", "");
                }

//                if (XaUtil.isEmpty(user.getEntraceState()))
//                {
//                    columnsName1.put("entranceState", "");
//                }else
//                {
//                    columnsName1.put("entranceState", user.getEntraceState());
//                }
                if(StringUtils.isNotBlank(user.getUserCompany()))
                {
        			columnsName1.put("userCompany", user.getUserCompany());
        		
                }else{	columnsName1.put("userCompany", "");}
                if(StringUtils.isNotBlank(user.getIndustry()))
                {
                	int i=0;
                	try {
						i=Integer.parseInt( user.getIndustry());
						columnsName1.put("industry",bootarea[i]);
					} catch (NumberFormatException e) {
						columnsName1.put("industry","");
					}
                	
                }else
                {
                	columnsName1.put("industry","");
                }
                if(StringUtils.isNotBlank(user.getUserEmail()))
                {
                	columnsName1.put("userEmail", user.getUserEmail());	
                }else
                {
                	columnsName1.put("userEmail","");	
                }
             
    		
				list1.add(columnsName1);
			}
			HSSFWorkbook wb =ExportExcel.CreateExcel("用户列表", columnsName, list1);


			OutputStream ops = null;
			try {
				ops = response.getOutputStream();
				response.reset();
				response.setContentType("application/vnd.ms-excel; charset=utf-8");
				response.setHeader("Content-Disposition", "attachment; filename=user.xls");
				wb.write(ops);
				ops.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if(ops != null) {
						ops.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}//结束批量导出
		Page<UserInfo> data = userInfoService.findUserDataByFilter(filterParams,pageable);
		
		
		request.setAttribute("json", JSON.toJSONString(data));
		request.setAttribute("currentPage", ++nextPage);
		
		request.setAttribute("userName", userName);
		request.setAttribute("userPhone", userPhone);
		request.setAttribute("userType", userType);
		request.setAttribute("entraceState", entraceState);
		request.setAttribute("pwd", pwd);
		
				
		return "userList";	
	}
	
	/**
	 * 详情 --页面
	 */
	@RequestMapping(value="userDetailByUserIdPage")
	public String userDetailByUserIdPage(HttpServletRequest request,@RequestParam(value="userId",defaultValue="")Integer userId){
		UserInfo user = userInfoService.findOne(userId);
		request.setAttribute("user", user);
		return "userDetail";
		
	}
	/**
	 * 新建 --页面
	 */
	@RequestMapping(value="userCreatePage")
	public String userCreatePage(){
		return "userCreate";
		
	}
	/**
	 * 新建 --数据库 保存
	 */
	@RequestMapping(value="userSave")
	public String userSave(HttpServletRequest request,@RequestParam("userPhoto2") MultipartFile file,UserInfo user){
		Admin admin =(Admin) request.getSession().getAttribute("admin");
		if(admin!=null)
		{
			if("en".equals(admin.getLang()))//英文
			{
				user.setZhOren(2);;
			}else if("cn".equals(admin.getLang()))//中文
			{
				user.setZhOren(1);
			} 
		}
		if(file!=null&&!file.isEmpty()){
			try {
				user.setUserPhoto(FolderPath.uploadFile(request, file, FolderPath.userphoto,".png"));
			} catch (IOException e) {}
		}
		user.setUserPhoto("img/head002.png");
		userInfoService.save(user);
		return "redirect:/user/userList";
		
	}
	
	/**
	 * 禁止登陆 --页面
	 */
	@RequestMapping(value="userForbid")
	public String userForbid(@RequestParam(value="userId",defaultValue="")Integer userId){
		userInfoService.userForbid(userId);
		return "redirect:/user/userList";
		
	}
	/**
	 * 允许登陆 --页面
	 */
	@RequestMapping(value="userAllow")
	public String userAllow(@RequestParam(value="userId",defaultValue="")Integer userId){
		userInfoService.userAllow(userId);
		return "redirect:/user/userList";
		
	}
	/**
	 * 修改 --页面
	 */
	@RequestMapping(value="userUpdateByUserIdPage")
	public String userUpdateByUserIdPage(HttpServletRequest request,@RequestParam(value="userId",defaultValue="")Integer userId){
		UserInfo user = userInfoService.findOne(userId);
		request.setAttribute("user", user);
		return "userUpdate";
		
	}
	/**
	 * 修改 --数据库保存
	 */
	@RequestMapping(value="userUpdateByUserIdSave")
	public String userUpdateByUserIdSave(HttpServletRequest request,UserInfo user,@RequestParam("userPhoto2") MultipartFile file){
		if(file!=null&&!file.isEmpty()){
			try {
				user.setUserPhoto(FolderPath.uploadFile(request, file, FolderPath.userphoto,".png"));
			} catch (IOException e) {}
		}
		//Admin admin =(Admin) request.getSession().getAttribute("admin");
		
		userInfoService.userUpdateByUserIdSave(user);
		
		return "redirect:/user/userList";
		
	}
	
	/**
	 * 初始化密码：手机号后6位
	 */
	
	@RequestMapping(value="userPwdChuShiHua")
	public String userPwdChuShiHua(HttpServletRequest request,@RequestParam(value="userId",defaultValue="")Integer userId,
			@RequestParam(value="pwd",defaultValue="")String pwd){
		if(!StringUtils.isNotBlank(pwd))
		{
			UserInfo user = userInfoService.userPwdChuShiHua(userId);
			if(user.getUserPassword().equals(user.getUserPhone().substring(user.getUserPhone().length()-6,user.getUserPhone().length()))){
				
				return "redirect:/user/userList?pwd=success";
			}
		} 
		return "redirect:/user/userList";
		
	}
}
